package com.cloudspace.jindun.fragment.xiaoxi;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.cloudspace.jindun.JindunApp;
import com.cloudspace.jindun.R;
import com.cloudspace.jindun.adapter.QunliaoiListAdapter;
import com.cloudspace.jindun.constants.Constants;
import com.cloudspace.jindun.ext.aq.AQUtility;
import com.cloudspace.jindun.log.APPLog;
import com.cloudspace.jindun.manager.MessageNumberManager;
import com.cloudspace.jindun.model.Qunliao;
import com.cloudspace.jindun.network.url.YXHttpUrl;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.ObjUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class GroupChatFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    public static final String TAG = GroupChatFragment.class.getSimpleName();

    public static GroupChatFragment instance = null;

    public static GroupChatFragment getInstance() {
        if (instance == null) {
            instance = new GroupChatFragment();
        }
        return instance;
    }

    public GroupChatFragment() {
        // Required empty public constructor
    }

    private ListView mListView;
    private QunliaoiListAdapter mQunliaoiListAdapter;
    private SwipeRefreshLayout mSwipeLayout;
    private Qunliao mQunliao;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_qunliao, container, false);
        initView(rootView);
        initData();
        setListener();
        return rootView;
    }

    private void initView(View view) {
        mListView = (ListView) view.findViewById(R.id.qunliao_lv);
        mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_qunliao);
    }

    private void initData() {
        mQunliaoiListAdapter = new QunliaoiListAdapter(getContext());
        mListView.setAdapter(mQunliaoiListAdapter);
    }

    private BroadcastReceiver redDotReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (mQunliaoiListAdapter != null){
                APPLog.zxhLog(TAG + " receive red dot broadcast");

                mQunliaoiListAdapter.notifyDataSetChanged();
            }
        }
    };

    private void registerReceiver(){
        if (isAdded()){
            IntentFilter filter = new IntentFilter(Constants.RED_DOT_BROADCAST_INTENT_ACTION);
            getContext().registerReceiver(redDotReceiver, filter);

            LocalBroadcastManager.getInstance(JindunApp.getInstance()).registerReceiver(messageReceiver,
                    new IntentFilter(Constants.MESSAGE_BROADCAST));
        }
    }

    private void unregisterReceiver(){
        if (isAdded()){
            getContext().unregisterReceiver(redDotReceiver);

            LocalBroadcastManager.getInstance(JindunApp.getInstance()).unregisterReceiver(messageReceiver);
        }
    }

    @Override
    public void onStart() {
        super.onStart();

        registerReceiver();
    }

    @Override
    public void onStop() {
        super.onStop();

        unregisterReceiver();
    }

    private void setListener() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mQunliao != null && mQunliao.getData() != null && mQunliao.getData().size() > 0) {
                    RongIM.getInstance().startGroupChat(getActivity(),
                            mQunliao.getData().get(position).getChannelId(),
                            mQunliao.getData().get(position).getChannelName());

                    MessageNumberManager.getInstance().readMessage(mQunliao.getData().get(position).getChannelId());
                    mQunliaoiListAdapter.notifyDataSetChanged();
                }

            }
        });
        mSwipeLayout.setOnRefreshListener(this);
    }

    private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            APPLog.zxhLog(TAG + " messageReceiver receive");

            AQUtility.post(new Runnable() {
                @Override
                public void run() {
                    if (mQunliaoiListAdapter != null){
                        mQunliaoiListAdapter.notifyDataSetChanged();
                    }
                }
            });
        }
    };


    @Override
    public void onRefresh() {
        if (mQunliao != null) {
            mQunliaoiListAdapter.clear();
        }
        requestData(YXHttpUrl.XX_HQLB, UserSessionManager.getInstance().getUserId());
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mQunliao != null) {
            mQunliaoiListAdapter.clear();
        }
        requestData(YXHttpUrl.XX_HQLB, UserSessionManager.getInstance().getUserId());
    }

    private void requestData(String url, String reportId) {
        OkHttpUtils.get()
                .url(url + reportId)
                .build()
                .execute(new StringCallback() {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mSwipeLayout.setRefreshing(false);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("----->", response);
                        if (response != null) {
                            Gson gson = new Gson();
                            mQunliao = gson.fromJson(response, Qunliao.class);

                            if (mQunliao != null &&
                                    mQunliao.getStatus() == 200){
                                mQunliaoiListAdapter.addAll(mQunliao.getData());
                                mSwipeLayout.setRefreshing(false);

                                refreshMsgUnreadCount(mQunliao.getData());
                            }
                        }
                    }
                });
    }

    private void refreshMsgUnreadCount(List<Qunliao.DataBean> datas) {
        if (ObjUtil.isEmpty(datas)){
            return;
        }

        for (final Qunliao.DataBean data : datas){
            RongIM.getInstance().getUnreadCount(Conversation.ConversationType.GROUP,
                    data.getChannelId(), new RongIMClient.ResultCallback<Integer>() {
                        @Override
                        public void onSuccess(Integer integer) {
                            if (integer > 0){
                                APPLog.zxhLog(TAG + String.format("channel %s has unread message count:%d",
                                        data.getChannelId(), integer));
                                MessageNumberManager.getInstance().addMessageUnread(data.getChannelId());
                                mQunliaoiListAdapter.notifyDataSetChanged();
                            }
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {

                        }
                    });
        }
    }
}
